<!--
 * @Description: 添加商品
 * 
 * @Author: XiongYaoYuan<xiongyaoyuan>
 * @Date: 2023-06-10 14:47:18
 * @FilePath: /yuxiuproweb/src/views/app/product/mods/add.vue
-->
<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="title"
    :visible.sync="shows"
    width="1100px"
    append-to-body
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="110px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="宝贝名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入宝贝名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="宝贝销售别名" prop="alias">
            <el-input v-model="form.alias" placeholder="请输入宝贝销售别名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="描述" prop="info">
            <el-input v-model="form.info" placeholder="请输入描述" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="是否启用" prop="enableFlag">
            <el-switch
              v-model="form.enableFlag"
              active-value="Y"
              inactive-value="N"
            ></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="标签" prop="label">
            <el-input v-model="form.label" placeholder="请输入标签" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="类型" prop="type">
            <el-select
              v-model="form.type"
              placeholder="请选择类型"
              style="width: 100%"
              @change="handleGoodsType(form.type)"
            >
              <el-option
                v-for="item in dict.type.goods_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="宝贝关联SKU" prop="babyTypes">
            <el-select
              v-model="form.babyTypes"
              placeholder="请选择宝贝关联SKU"
              style="width: 100%"
              clearable
              filterable
              multiple
              @change="handleBabyChange"
            >
              <el-option
                v-for="item in babyList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-tabs
        v-if="babySKUList.length"
        v-model="editableTabsValue"
        closable
        @tab-remove="removeTab"
      >
        <el-tab-pane
          v-for="item in babySKUList"
          :key="item.id"
          :label="item.name"
          :name="item.id"
          style="padding-top: 10px"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item label="SKU别名" prop="alias">
                <el-input v-model="item.alias" placeholder="请输入SKU别名" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="主图">
            <image-preview :src="item.homeImage" :width="120" :height="120" />
          </el-form-item>
          <el-form-item label="轮播图" prop="banner">
            <image-preview :src="item.banner" :width="120" :height="120" />
          </el-form-item>
          <el-form-item label="瀑布图" prop="waterfallPlot">
            <image-preview
              :src="item.waterfallPlot"
              :width="120"
              :height="120"
            />
          </el-form-item>
          <el-col :span="8">
            <el-form-item label="推荐搭配" prop="recommendedPairingIds">
              <el-select
                v-model="item.recommendedPairingIds"
                placeholder="请选择推荐搭配"
                style="width: 100%"
                clearable
                filterable
                multiple
              >
                <template v-if="form.type === '0'">
                  <el-option
                    v-for="item in decorateList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </template>
                <template v-else>
                  <el-option
                    v-for="item in curtainList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </template>
              </el-select>
            </el-form-item>
          </el-col>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="shows = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getProduct, addProduct, updateProduct } from "@/api/app/product";
import { listCurtain as getCurtainList } from "@/api/goods/curtain";
import { listCurtain as getDecorateList } from "@/api/goods/decorate";
import { listRawMaterial as getMaterialList } from "@/api/goods/material";
import { listImage } from "@/api/app/image";

export default {
  dicts: ["goods_type"],
  props: {
    show: Boolean,
    type: {
      type: String,
      default: "add",
    },
    data: {
      type: Object,
    },
  },
  data() {
    return {
      // 表单参数
      form: {
        productId: null,
        name: null,
        alias: null,
        info: null,
        enableFlag: "N",
        label: null,
        type: null,
        babyTypes: null,
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "宝贝名称不能为空", trigger: "change" },
        ],
        type: [{ required: true, message: "请选择类型", trigger: "change" }],
        babyTypes: [
          { required: true, message: "请选择宝贝关联SKU", trigger: "change" },
        ],
      },

      editableTabsValue: null,
      babyList: [],
      curtainList: [],
      decorateList: [],
      materialList: [],
      babySKUList: [],
    };
  },
  computed: {
    title() {
      return {
        add: "添加商品",
        edit: "修改商品",
      }[this.type];
    },
    shows: {
      get() {
        return this.show;
      },
      set(newValue) {
        this.$emit("update:show", newValue);
      },
    },
  },
  async created() {
    // new Promise.all([
    //   this.getCurtainList(),
    //   this.getDecorateList(),
    //   this.getMaterialList(),
    // ]).then((res) => {
    //   console.log("123");
    // });
    await this.getCurtainList();
    await this.getDecorateList();
    await this.getMaterialList();
    if (this.type === "edit") {
      this.handleUpdate();
    }
  },
  methods: {
    // 获取app显示图片
    async getImageList(productId, type) {
      const { rows } = await listImage({
        productId,
        type,
      });
      return rows?.length ? rows[0] : {};
    },
    // 获取窗帘
    async getCurtainList() {
      const { rows } = await getCurtainList({
        pageNum: 1,
        pageSize: 1000,
      });
      this.curtainList = rows?.map((e) => {
        return {
          ...e,
          id: `${e.customCurtainId}`,
          type: "0",
        };
      });
    },

    // 获取窗幔
    async getDecorateList() {
      const { rows } = await getDecorateList({
        pageNum: 1,
        pageSize: 1000,
      });
      this.decorateList = rows?.map((e) => {
        return {
          ...e,
          id: `${e.customWindowCurtainId}`,
          type: "1",
        };
      });
    },

    // 获取原料
    async getMaterialList() {
      const { rows } = await getMaterialList({
        pageNum: 1,
        pageSize: 1000,
      });
      this.materialList = rows?.map((e) => {
        return {
          ...e,
          id: `${e.rawMaterialId}`,
          type: "2",
        };
      });
    },

    /** 修改按钮操作 */
    handleUpdate() {
      getProduct(this.data.productId).then(async ({ data }) => {
        this.form = {
          ...data,
          babyTypes: data.skuList?.map((e) => `${e.skuCorrelationId}`),
        };
        this.handleGoodsType(this.form.type, "init");

        const babySKUList = await Promise.all(
          data.skuList?.map(async (e) => {
            const item =
              this.babyList?.find(
                (v) => `${v.id}` === `${e.skuCorrelationId}`
              ) || {};
            const image = await this.getImageList(item.id, item.type);
            return {
              ...e,
              name: item?.name || "",
              id: item?.id || "",
              homeImage: image?.homeImage || "",
              banner: image?.banner || "",
              waterfallPlot: image?.waterfallPlot || "",
              recommendedPairingIds: e.recommendedPairingIds
                ? e.recommendedPairingIds.split(",")
                : [],
            };
          })
        );

        this.babySKUList = babySKUList;
        this.editableTabsValue = this.babySKUList?.[0]?.id;
      });
    },

    // 切换类型获取数据
    handleGoodsType(val, status = "") {
      switch (val) {
        case "0":
          this.babyList = this.curtainList;
          break;
        case "1":
          this.babyList = this.decorateList;
          break;
        case "2":
          this.babyList = this.materialList;
          break;
        default:
          break;
      }
      if (status !== "init") {
        this.form.babyTypes = null;
        this.babySKUList = [];
        this.editableTabsValue = null;
      }
    },

    // 获取下列数据
    async handleBabyChange(list) {
      const babySKUList = await Promise.all(
        list?.map(async (e) => {
          const item = this.babyList?.find((v) => v.id === e) || {};
          const image = await this.getImageList(item.id, item.type);
          return {
            ...item,
            homeImage: image?.homeImage || "",
            banner: image?.banner || "",
            waterfallPlot: image?.waterfallPlot || "",
            alias: "",
            recommendedPairingIds: null,
          };
        })
      );
      this.babySKUList = babySKUList;
      this.editableTabsValue = list.length ? list[0] : null;
    },

    removeTab(targetName) {
      let tabs = this.babySKUList;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.id === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.id;
            }
          }
        });
      }

      this.editableTabsValue = activeName;
      this.babySKUList = tabs.filter((tab) => tab.id !== targetName);
      this.form.babyTypes = this.babySKUList?.map((e) => e.id);
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const skuList = this.babySKUList?.map((e) => {
            return {
              alias: e.alias,
              productId: this.form.productId || null,
              productSkuId: e.productSkuId,
              recommendedPairingIds: e.recommendedPairingIds?.join(),
              skuCorrelationId: e.id,
            };
          });
          this.form.skuList = skuList;
          if (this.form.productId != null) {
            updateProduct(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.shows = false;
              this.$emit("update");
            });
          } else {
            addProduct(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.shows = false;
              this.$emit("update");
            });
          }
        }
      });
    },
  },
};
</script>
